import { ProCardTabsProps } from '@ant-design/pro-card/lib';

import daishenhe from '@/assets/img/daishenhe.png';
import payimg from '@/assets/img/pay.png';
import weishenhe from '@/assets/img/weishenhe.png';
import yishenhe from '@/assets/img/yishenhe.png';
import {
  auditWithdrawalInfo,
  getWithdrawalInfo,
  withdrawalStatus,
} from '@/services/sys/log';
import {
  ModalForm,
  ProCard,
  ProDescriptions,
  ProFormInstance,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { PageHeader, WaterMark } from '@ant-design/pro-layout';
import { useRequest } from 'ahooks';
import React, { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router';

import { getResult } from '@/services/sys/attribute';
import { InboxOutlined, PlusOutlined } from '@ant-design/icons';
import { StatisticCard } from '@ant-design/pro-card';
import {
  Avatar,
  Button,
  Flex,
  Image,
  message,
  Popconfirm,
  Typography,
  Upload,
} from 'antd';
import { UploadChangeParam } from 'antd/es/upload';
import { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
interface Props {
  params: {
    userId: string;
  };
}
const { Paragraph } = Typography;
const { Dragger } = Upload;
let pywtstatus = await getResult('paymentwithdrawalStatus', 0);

const columns = [
  {
    title: '经销商',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '提现金额',
    dataIndex: 'requestAmount',
    valueType: 'money',
    key: 'requestAmount',
  },
  {
    title: '手续费',
    dataIndex: 'taxes',
    valueType: 'money',
    key: 'taxes',
  },
  {
    title: '实际金额',
    dataIndex: 'amount',
    valueType: 'money',
    key: 'amount',
  },

  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    key: 'status',
    valueEnum: pywtstatus,
  },

  {
    title: '收款人姓名',
    dataIndex: 'authName',
    valueType: 'authName',
    key: 'authName',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '申请时间',
    dataIndex: 'updateDate',
    valueType: 'dateTime',
  },
  {
    title: '发票编号',
    dataIndex: 'auditSn',
    //  valueType: 'dateTime',
  },
  {
    title: '发票备注',
    dataIndex: 'auditRemark',
    //   valueType: 'dateTime',
  },
];

const columnsBankInfo = [
  {
    title: '提现方式',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '卡号',
    dataIndex: 'cardNo',
    key: 'cardNo',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '客户',
    dataIndex: 'userName',
  },
  {
    title: '收款码',
    dataIndex: 'image',
    valueType: 'image',
  },
  {
    title: '地址',
    dataIndex: 'address',
    valueType: 'address',
  },
];

interface withdrawData {
  auditRemark: string;
  id: number;
  auditSn: string;
  auditImage: number;
  auditImageUrl: string;
}

const Show: React.FC<any> = () => {
  const [tab, setTab] = useState('tab1');
  const [tabPosition, setTabPosition] =
    useState<ProCardTabsProps['tabPosition']>('left');
  const params = useParams();
  const { data, loading, refresh, error, run } = useRequest(getWithdrawalInfo, {
    manual: true,
  });
  const [wDataInfo, setWDataInfo] = useState<withdrawData>({
    auditImage: 0,
    id: 0,
    auditImageUrl: '',
    auditSn: '',
    auditRemark: '',
  });
  useEffect(() => {
    if (params?.id) {
      // @ts-ignore
      run(params?.id);
    }
  }, [params, run]);

  const getWorkImage = () => {
    let status = data?.status;
    if (status == 1) {
      return yishenhe;
    }
    if (status == 3) {
      return weishenhe;
    }
    if (status == 2) {
      return daishenhe;
    }
  };
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }

    return isJpgOrPng && isLt2M;
  };
  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    console.log('handleChange', info);

    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      // @ts-ignore
      let data = info?.file?.response?.data;
      let p = { ...wDataInfo, auditImage: data?.id, auditImageUrl: data?.url };
      setWDataInfo(p);
      // Get this url from response in real world.
      // getBase64 ( info.file.originFileObj as RcFile, url => {
      //   setLoading ( false );
      //  setImageUrl ( url );
      //
      // } );
    }
  };
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // @ts-ignore
  const formRef = useRef<ProFormInstance<withdrawData>>();
  const formatNumber = (n: string) => {
    n = n.toString();
    return n[1] ? n : `0${n}`;
  };
  const formatTimeAll = (date: {
    getFullYear: () => any;
    getMonth: () => number;
    getDate: () => any;
    getHours: () => any;
    getMinutes: () => any;
    getSeconds: () => any;
  }) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return (
      [year, month, day].map(formatNumber).join('-') +
      ' ' +
      [hour, minute, second].map(formatNumber).join(':')
    );
  };

  const getCopyText = () => {
    //  let data = dataInfo?.data;
    // @ts-ignore
    let arr: [any] = [];
    arr.push('姓名:' + data?.name);
    arr.push('订单号:' + data?.sn);
    arr.push('提现金额:' + data?.requestAmount);
    arr.push('申请时间:' + formatTimeAll(new Date(data?.createDate)));
    arr.push('提现方式:' + data?.bankInfo?.name);
    arr.push('卡号:' + data?.bankInfo?.cardNo);
    arr.push('手机号:' + data?.bankInfo?.phone);
    arr.push('地址:' + data?.bankInfo?.address);

    let s = arr.join(';\n\t\t');
    return s;
  };
  return (
    <WaterMark
      width={150}
      height={150}
      image={getWorkImage()}
      fontColor={'#e20808'}
    >
      <ProCard
        loading={loading}
        title={
          <PageHeader
            className="site-page-header"
            onBack={() => window.history.back()}
            title={
              <StatisticCard
                loading={loading}
                statistic={{
                  title: (
                    <Paragraph copyable={{ text: getCopyText() }}>
                      {data?.authName}
                    </Paragraph>
                  ),
                  value: data?.requestAmount,
                  suffix: '￥',
                  precision: 2,
                  valueStyle: {
                    color: '#ba040a',
                  },
                  icon: <Avatar size={68} src={data?.avatar} />,
                }}
              />
            }
            subTitle={data?.sn}
          />
        }
        extra={
          <>
            <Flex gap="small" wrap>
              {data?.status == 2 ? (
                <ModalForm<withdrawData>
                  title="发票上传"
                  formRef={formRef}
                  trigger={
                    <Button type="primary" size="middle" ghost={true}>
                      <PlusOutlined />
                      发票上传
                    </Button>
                  }
                  initialValues={wDataInfo}
                  onChange={() => {
                    setWDataInfo({ ...data });
                  }}
                  submitTimeout={2000}
                  onFinish={(values) => {
                    setWDataInfo({ ...values });
                    //   console.log ( wDataInfo );

                    return new Promise((resolve, reject) => {
                      auditWithdrawalInfo(wDataInfo)
                        .then((res) => {
                          if (res.success) {
                            resolve(true);

                            message.success('提交成功');
                            run(wDataInfo?.id);
                          } else {
                            message.error('操作失败');
                            reject(false);
                          }
                        })
                        .catch((e) => {
                          message.error('操作失败');

                          reject(false);
                        });
                    });
                    //   return true;
                  }}
                >
                  <ProFormText hidden={true} name="id" label="支付编号" />
                  <Dragger
                    accept="jpg,png,jpeg"
                    name="file"
                    className="avatar-uploader"
                    showUploadList={false}
                    action={'/api/upload/image?type=10'}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                  >
                    {wDataInfo?.auditImage > 0 ? (
                      <Image src={wDataInfo?.auditImageUrl} />
                    ) : (
                      <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                      </p>
                    )}
                    <p>图片上传...</p>
                  </Dragger>
                  <ProFormText
                    required={true}
                    name="auditSn"
                    label="支付编号"
                  />
                  <ProFormTextArea name="auditRemark" label="备注" />
                </ModalForm>
              ) : (
                ''
              )}
              {data?.status == 2 ? (
                <Popconfirm
                  title={'通过确定吗！'}
                  onConfirm={() => {
                    withdrawalStatus(data?.id, 1).then((res) => {
                      refresh();
                    });
                  }}
                >
                  <Button type="primary">通过</Button>{' '}
                </Popconfirm>
              ) : (
                ''
              )}

              {data?.status == 2 ? (
                <Popconfirm
                  title={'未通过确定吗！'}
                  onConfirm={() => {
                    withdrawalStatus(data?.id, 3).then((res) => {
                      refresh();
                    });
                  }}
                >
                  <Button type="primary" danger>
                    未通过
                  </Button>{' '}
                </Popconfirm>
              ) : (
                ''
              )}
            </Flex>
          </>
        }
        bordered={false}
      >
        <ProDescriptions title="基本信息" dataSource={data} columns={columns} />
        <ProDescriptions
          title="提现信息"
          dataSource={data?.bankInfo}
          columns={columnsBankInfo}
        />
        <Image
          fallback={payimg}
          preview={data?.auditImageUrl != null}
          src={data?.auditImageUrl}
        />
      </ProCard>
    </WaterMark>
  );
};
export default Show;
